package com.scs.application.core.utils;

import com.scs.application.core.exceptions.BusinessException;
import com.google.common.collect.Lists;

import java.util.List;

/**
 * @Description:
 */
public class BeanUtils extends org.springframework.beans.BeanUtils {

    /**
     * @param sourceList
     * @param targetList
     * @param targetClass
     * @param useBeanCopier 使用 {@link BeanCopierUtils} 提升性能，仅限非链式调用
     * @param <S>
     * @param <T>
     */
    public static <S, T> void copyProperties(List<S> sourceList, List<T> targetList, Class<T> targetClass, boolean useBeanCopier) {
        T target = null;

        for (S source : sourceList) {
            try {
                target = (T) targetClass.newInstance();
            } catch (Exception e) {
                throw new BusinessException("服务器错误");
            }
            if (useBeanCopier) {
                BeanCopierUtils.copy(source, target);
            } else {
                BeanUtils.copyProperties(source, target);
            }
            targetList.add(target);
        }
    }

    public static <S, T> void copyProperties(List<S> sourceList, List<T> targetList, Class<T> targetClass) {
        copyProperties(sourceList, targetList, targetClass, false);
    }

    public static <S, T> List<T> copyProperties(List<S> sourceList, Class<T> targetClass, boolean useBeanCopier) {
        List<T> targetList = Lists.newArrayListWithExpectedSize(sourceList.size());
        copyProperties(sourceList, targetList, targetClass, useBeanCopier);
        return targetList;
    }


    public static <S, T> List<T> copyProperties(List<S> sourceList, Class<T> targetClass) {
        List<T> targetList = Lists.newArrayListWithExpectedSize(sourceList.size());
        copyProperties(sourceList, targetList, targetClass);
        return targetList;
    }


}

